"""
@-*- coding: utf-8 -*-
@ python: 3.12.3
@ 创建者: JacksonCode
@ 创建时间: 2025-09-29
"""

"""
JsonCompare.py
1. 两份 JSON 横向 diff（新增/删除/变更）
2. 单份 JSON 内部体检（重复 code、测试数据、URL 探活）
用法：
    # 横向：比较两次返回
    python JsonCompare.py old.json new.json

    # 纵向：只检查当前这份
    python JsonCompare.py bank_list.json
"""
import json
import sys
from collections import Counter
from typing import Dict, List, Set, Tuple
import difflib
try:
    import requests  # 可选：pip install requests
    HAS_REQUESTS = True
except ImportError:
    HAS_REQUESTS = False


# ---------- 工具 ----------
def load(path: str) -> Dict:
    """支持文件或原始 JSON 字符串"""
    try:
        with open(path, encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        return json.loads(path)


def url_alive(url: str, timeout: int = 5) -> bool:
    """HEAD 请求，返回是否 200"""
    if not HAS_REQUESTS:
        return True  # 没装 requests 就跳过
    try:
        return requests.head(url.strip(), timeout=timeout).status_code == 200
    except Exception:
        return False


# ---------- 纵向体检 ----------
def self_check(js: Dict):
    print("【自检】")
    bank_list = js["data"]["bankList"]
    codes = [b["bankCode"] for b in bank_list]
    names = [b["bankName"] for b in bank_list]

    # 重复 code
    dup_code = [k for k, v in Counter(codes).items() if v > 1]
    if dup_code:
        print(" ❌ 重复 bankCode:", dup_code)
    else:
        print(" ✅ bankCode 无重复")

    # 重复 name
    dup_name = [k for k, v in Counter(names).items() if v > 1]
    if dup_name:
        print(" ⚠️  重复 bankName:", dup_name)
    else:
        print(" ✅ bankName 无重复")

    # 测试数据
    test_codes = {c for c in codes if c.lower() in {"test", "faker", "999999", "888888"}}
    test_codes |= {c for c in codes if c.startswith("test") or c.startswith("faker")}
    if test_codes:
        print(" ⚠️  疑似测试 bankCode:", list(test_codes))

    # URL 探活
    bad_url = []
    for b in bank_list:
        for k in ("bankUrl", "bgUrl"):
            if not url_alive(b[k]):
                bad_url.append((b["bankCode"], k))
    if bad_url:
        print(" ❌ 无法访问的 URL:", bad_url)
    else:
        print(" ✅ 所有 URL 返回 200")


# ---------- 横向 diff ----------
def diff(old: Dict, new: Dict):
    print("【横向对比】")
    old_map = {b["bankCode"]: b for b in old["data"]["bankList"]}
    new_map = {b["bankCode"]: b for b in new["data"]["bankList"]}

    added = new_map.keys() - old_map.keys()
    removed = old_map.keys() - new_map.keys()
    common = new_map.keys() & old_map.keys()

    if added:
        print(" ✅ 新增银行:", list(added))
    if removed:
        print(" ❌ 删除银行:", list(removed))

    changes = []
    for code in common:
        o, n = old_map[code], new_map[code]
        if o != n:
            # 只打印变化字段
            diff_fields = [k for k in o if o[k] != n[k]]
            changes.append((code, diff_fields))
    if changes:
        print(" ⚠️  字段变更:")
        for code, fields in changes:
            print("   ", code, fields)
    if not (added or removed or changes):
        print(" ✅ 两份 JSON 完全一致")


# ---------- CLI ----------
def main():
    if len(sys.argv) == 2:
        self_check(load(sys.argv[1]))
    elif len(sys.argv) == 3:
        diff(load(sys.argv[1]), load(sys.argv[2]))
    else:
        print("用法：\n  单份体检: python bank_list_check.py bank.json")
        print("  两份对比: python bank_list_check.py old.json new.json")
        sys.exit(1)


if __name__ == "__main__":
    main()